//
//  BankListController.swift
//  d11
//
//  Created by rhonin on 2018/11/3.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import SwiftyJSON
class BankListController: UpdateRootViewController,UITableViewDelegate,UITableViewDataSource {
    var array = Array<JSON>()
    var loadViews:MBProgressHUD?
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell  = tableView.dequeueReusableCell(withIdentifier: "banklistcell") as! BankTableViewCell
        let json = array[indexPath.row]
        cell.configself(dic: json)
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         let json = array[indexPath.row]
        self.setDefBank(dic: json,index: indexPath.row)
        
    }
    lazy var tableView: UITableView = {
        let tab = UITableView.init(frame: .zero, style: .plain)
        tab.separatorStyle = .none
        tab.register(UINib(nibName: "BankTableViewCell", bundle: nil), forCellReuseIdentifier: "banklistcell")
        tab.delegate = self
        tab.dataSource = self
        return tab
    }()
    lazy var footView: UIView = {
        //298
        //47.5
        let views = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 80))
        let button = UIButton(frame: CGRect(x: 0, y: 20, width: 298, height: 47.5))
        button.centerX = ScreenWidth/2
        button.setTitle("新增银行卡", for: .normal)
        button.addTarget(self, action: #selector(addBannk), for: .touchUpInside)
        views.addSubview(button)
        let layerGradientCodes = CAGradientLayer()
        layerGradientCodes.colors = [
            UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
            UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
        ]
        layerGradientCodes.frame = CGRect(x: 0, y: 0, width: button.frame.width, height: button.frame.height+50)
        button.layer.addSublayer(layerGradientCodes)
        button.layer.cornerRadius = 5
        button.clipsToBounds = true
        return views
    }()
    
   @objc func addBannk() {
        checkForAuthority()

    }
    var hud : MBProgressHUD?
    func checkForAuthority() {
        let vc = UpdateBankViewController()
        let item = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
        self.navigationItem.backBarButtonItem = item
        self.navigationController?.pushViewController(vc, animated: true)
       
    }
  
   
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.addSubview(tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        self.tableView.tableHeaderView = footView
        self.title = "取款银行卡"
        
       // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
        
        self.tableView.estimatedRowHeight = 100;
        self.tableView.rowHeight = UITableView.automaticDimension;
    }

    override func viewWillAppear(_ animated: Bool) {
        weak var this  = self
        RequestHelper.post(atPath: "/clientsAPIs/GetWithdrawBankList", withData: Dictionary(), withCompletion: { data in
            
            let json = JSON(data)
             print("个人信息-银行卡列表:\(json)")
            if json.arrayValue.count>0{
                this?.array = json.arrayValue
                DispatchQueue.main.async {
                    //  UIHelper.alertSimpleMessage(about: "绑定成功", withDescription: "", in: self)
                    this?.tableView.reloadData()
                }
            }else{
                DispatchQueue.main.async {
                    //   UIHelper.alertSimpleMessage(about: "绑定失败", withDescription: json["msg"].stringValue, in: self)
                }
            }
        },withError: {_ in
            
             UIHelper.alertSimpleMessage(about: "服务器异常，\(getErrorString())", withDescription: "", in: self)
        })
        
    }
    
    func setDefBank(dic:JSON,index:Int) -> Void {
        loadViews = MBProgressHUD.showMessageNoHiden("正在提交.", to: self.view)
        weak var this = self;
        let wdbankid  = dic["wdbankid"].stringValue
        RequestHelper.post(atPath: "/clientsAPIs/SetDefaultWithdrawBank", withData: ["wdbankid":wdbankid],withCompletion:{ data in
            let json = JSON(data)
            print("用于设置默认取款卡:\(json)")
            DispatchQueue.main.async {
             let success =  json["success"].bool ?? false
             let msg = json["msg"].string ?? ""
                if success == true {
                for (i,item) in self.array.enumerated(){
                      var dict = item
                        if item["defaultcard"].string ?? "0" == "1"{
                            dict["defaultcard"] = "0"
                            self.array[i] = dict
                        }
                    }
                   var tempDic = dic
                    tempDic["defaultcard"] = "1"
                    self.array[index] = tempDic
                    self.tableView.reloadData()
                }
                UIHelper.alertSimpleMessage(about: msg, withDescription: "", in: self)
                this?.loadViews?.removeFromSuperview()
                
            }
        },withError: {_ in
            DispatchQueue.main.async {
                this?.loadViews?.removeFromSuperview()
                 UIHelper.alertSimpleMessage(about: "服务器异常，\(getErrorString())", withDescription: "", in: self)
            }
           
        })
    }
}
